var http = require('http');
var url = require('url');
var util = require('util');

const fs = require('fs');
 

// 访问接口
// http://localhost:9527/chart/list?pageSize=10&pageNumber=0&sort=star

http.createServer(function(req, res){
  // console.log(req.url);
  // console.log(req.method);
  // console.log(req.headers);
  // get请求
  if (req.method = 'GET') {
    // 解析请求路径
    var oUrl = url.parse(req.url, true);
    // 解析 url 参数
    var param = url.parse(req.url, true).query;

    res.writeHead(200,{
      "Content-Type":'text/html',
      'charset':'utf-8',
      'Access-Control-Allow-Origin':'*',
      'Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'
    });//可以解决跨域的请求

    var resParam = {
      code: 200,
      data: null,
      message: ''
    }

    // 图标列表
    if (oUrl.pathname == '/chart/list') {
      sortList(param).then(list => {
        resParam.data = list;
        console.log('aaaaaaa')
        console.log(list.length);
        res.write(JSON.stringify(resParam));
        res.end();
      }).catch(() => {
        resParam.code = 500;
        resParam.message = '获取列表失败';
        res.write(JSON.stringify(resParam));
        res.end();
      })
    }
  }

}).listen(9527, function () {
  console.log('服务运行在 http://127.0.0.1:9527');
});


// sortList({
//   pageSize: 10,
//   pageNumber: 0,
//   sort: 'viewCount'
// }).then(list => {
//   console.log(list);
// })

function sortList (param) {
  return new Promise((aResolve, aReject) => {
    var path = './echarts/index/';
    fs.readdir(path, function (err, files) {
      if (err) {
        return console.log('文件夹读取失败');
      }
      var aProm = [];
      files.forEach((item,index) => {
        aProm.push(new Promise((bResolve, bReject) => {
          var filename = path + item;
          fs.readFile(filename, function (err, data) {
            if (err) {
              return addLogs(`文件读取失败：${filename}`);
              bReject();
            }
            data = data.toString().split('\n');
            var arr = [];
            data.forEach((aItem, aIdx) => {
              // 最后一行是空
              if (aItem.length < 10) {
                return;
              }
              var obj = JSON.parse(aItem);
              var name = '';
              switch (param.sort) {
                case 'starCount': name = 's'; break;
                case 'viewCount': name = 'v'; break;
                case 'lastUpdateTime': name = 'l'; break;
              }
              var res = {
                cid: obj.c,
                s: obj[name]
              }
              arr.push(res);
            })
            bResolve(arr);
          })
        }))
      })
      Promise.all(aProm).then((data) => {
        var list = []; 
        data.forEach(item => {
          list = list.concat(item);
        })
        list = list.sort((prev, next) => {
          return prev.s - next.s > 0 ? -1 : 1;
        })
        // 返回分页数据
        list = setPaging(list, param);
        getListInfo(list).then(infoList => {
          console.log(infoList.length);
          aResolve(infoList);
        }).catch(() => {
          aReject();
        })
      }).catch(() => {
        aReject();
      })
    })
  })
}

// 分页
function setPaging (list, param) {
  var start = param.pageNumber * param.pageSize;
  var end = start + param.pageSize;
  return list.slice(start, end);
}

// 获取列表详情
function getListInfo (list) {
  return new Promise((aResolve, aReject) => {
    var aProm = [];
    list.forEach((aItem,aIndex) => {
      var filename = `./echarts/data/${aItem.cid}.txt`;
      aProm.push(new Promise((bResolve, bReject) =>{
        fs.readFile(filename, function (err, data) {
          if (!err) {
            bResolve(data.toString());
          } else {
            bReject();
          }
        })
      }));
    })
    Promise.all(aProm).then(data => {
      var res = data.map((item, index) => {
        var obj = JSON.parse(item);
        return {
          cid: obj.cid,
          title: obj.title,
          starCount: obj.starCount,
          viewCount: obj.viewCount,
          userName: obj.userName,
          avatar: obj.avatar
        }
      })
      aResolve(res);
    }).catch(() => {
      aReject();
    })
  })
}

// 添加错误日志
function addLogs (msg) {
  console.log(msg);
  msg = new Date().toLocaleString() + ' ' + msg + '\n';
  fs.appendFile(__dirname + '/logs/serve.log', msg, function(err) {
    if(err) {
      return console.log(err);
    }
  });
}






